package org.meow.aspect;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.meow.entity.Visit;
import org.meow.entity.Visitor;
import org.meow.result.Result;
import org.meow.service.VisitService;
import org.meow.service.VisitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * &#064;Date: 24/05/16-15:17
 * &#064;Description: 在公开接口或使用AutoLog注解的接口被访问时创建记录
 */
@Aspect
@Component
@Slf4j
public class AutoLogAspect {

  @Autowired
  private HttpServletRequest request;
  @Autowired
  private VisitorService     visitorService;
  @Autowired
  private VisitService       visitService;

  @Pointcut("execution(* org.meow.controller.api.*.*(..)) || @annotation(org.meow.annotation.AutoLog)")
  public void autoLogPointCut() {
  }

  @Around("autoLogPointCut()")
  public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("记录访问日志");
    Object result = joinPoint.proceed();

    String  ip      = request.getRemoteAddr();
    Visitor visitor = visitorService.queryByIp(ip);
    if (visitor == null) {
      visitor = new Visitor();
      visitor.setIpAddress(ip);
      visitor.setUserAgent(request.getHeader("User-Agent"));
      visitor.setCreatedAt(LocalDateTime.now());
      visitorService.save(visitor);
    }
    Visit visits = new Visit();
    visits.setUrl(request.getRequestURL().toString());
    visits.setVisitorId(visitor.getId());
    visits.setStatusCode(((Result<?>) result).getCode());
    visits.setCreatedAt(LocalDateTime.now());
    visitService.save(visits);
    return result;
  }
}
